import { Injectable, UseFilters } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { OrderEntity, OrderType, PayType } from 'src/modules/admin/order/entities/order.entity';
import { Between, FindOptionsWhere, Repository } from 'typeorm';
import { equals, isNil } from 'ramda';
import { GetOrderDto } from 'src/modules/admin/order/dto/order.dto';
import { getPagination, throwHttp } from 'src/utlis';
import { TokenDto } from 'src/common/auth/constants';
import { HttpExceptionFilter } from 'src/common/http-exception.filter';
import { IdDto } from 'src/common/dto/dto';
import { OrderState } from 'src/dictionaries/index.enum';
interface OrderData {
  amount: number;
  title: string;
  id: number;
  type: OrderType
}
@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(OrderEntity)
    private readonly OrderRepository: Repository<OrderEntity>,
  ) { }
  /** 获取订单 */
  async getOrderPage(params: GetOrderDto, operatorBy: TokenDto) {
    try {
      const {
        orderNo,
        status,
        createTimeStart,
        createTimeEnd,
        payType,
        type
      } = params;
      const where: GetOrderDto = {
        orderNo,
        status,
        userId: operatorBy.userId,
        payType,
        type
      };
      // 创建时间筛选
      if (!isNil(createTimeStart) && !isNil(createTimeEnd)) {
        where.createDate = Between(createTimeStart, createTimeEnd);
      }
      const { pageSize, pageNum } = getPagination({
        pageSize: params.pageSize,
        pageNum: params.pageNum,
      });
      const [data, total] = await this.OrderRepository.findAndCount({
        where,
        cache: true,
        order: { createDate: 'DESC' },
        skip: pageNum * pageSize,
        take: pageSize,
      });
      return {
        data,
        total,
        pageSize,
        pageNum: pageNum + 1,
      };
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 获取订单详情 */
  @UseFilters(new HttpExceptionFilter())
  async getOrderInfo(body: FindOptionsWhere<OrderEntity>, operatorBy: TokenDto) {
    try {
      return await this.OrderRepository.findOne({
        where: { ...body, userId: operatorBy.userId },
        cache: true,
      });
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 根据用户id、订单类型、状态获取订单数据 */
  @UseFilters(new HttpExceptionFilter())
  async getUserIdOrderInfo(payType: PayType, status: OrderState, operatorBy: TokenDto) {
    try {
      return await this.OrderRepository.find({
        where: { payType, status, userId: operatorBy.userId },
        cache: true,
      });
    } catch (error) {
      throwHttp(error.message);
    }
  }

  /**
* 创建订单
* @param queryRunner 查询运行器
* @param userId 用户ID
* @param data 更新用户数据
* @returns 是否成功
*/
  async createOrder(queryRunner, userId, data: OrderData): Promise<OrderEntity | undefined> {
    try {
      /** 创建消费记录 */
      const order = new OrderEntity()
      order.amount = data.amount
      order.title = `${data.title}` as string
      order.status = OrderState.COMPLETED
      order.payType = PayType.balancePay
      order.userId = userId
      const result = await queryRunner
        .manager
        .getRepository(OrderEntity)
        .save(order);
      return result;
    } catch (error) {
      console.log(error);
      await queryRunner.rollbackTransaction();
      return undefined;
    }
  }
}
